package cn.iocoder.yudao.module.wecom.dal.mysql.chatgroup;

import java.util.*;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.module.wecom.dal.dataobject.chatgroup.WeChatGroupDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.chatgroupmember.WeChatGroupMemberDO;
import org.apache.ibatis.annotations.Mapper;
import cn.iocoder.yudao.module.wecom.controller.admin.chatgroup.vo.*;

/**
 * 客户群 Mapper
 *
 * @author 数创万维
 */
@Mapper
public interface WeChatGroupMapper extends BaseMapperX<WeChatGroupDO> {
    default PageResult<WeChatGroupDO> selectPage(WeChatGroupPageReqVO reqVO) {
        MPJLambdaWrapperX<WeChatGroupDO> query = new MPJLambdaWrapperX<WeChatGroupDO>();
        // 如果指定了weUserId的情况，则需要leftJoin去获取指定员工所在的群聊列表，如果不指定WeUserId， 那么就是看全量的群聊列表
        if (StrUtil.isNotEmpty(reqVO.getWeUserId())) {
            if (Objects.nonNull(reqVO.getUserType())) {
                query.leftJoin(WeChatGroupMemberDO.class, WeChatGroupMemberDO::getChatId, WeChatGroupDO::getChatId)
                        .eq(WeChatGroupMemberDO::getUserType, reqVO.getUserType())
                        .eq(WeChatGroupMemberDO::getWeUserId, reqVO.getWeUserId())
                ;
            } else {
                query.leftJoin(WeChatGroupMemberDO.class, WeChatGroupMemberDO::getChatId, WeChatGroupDO::getChatId)
                        .eq(WeChatGroupMemberDO::getWeUserId, reqVO.getWeUserId())
                ;
            }
        }
        query.selectAll(WeChatGroupDO.class)
                .eqIfPresent(WeChatGroupDO::getChatId, reqVO.getChatId())
                .likeIfPresent(WeChatGroupDO::getName, reqVO.getName())
                .eqIfPresent(WeChatGroupDO::getOwner, reqVO.getOwner())
                .betweenIfPresent(WeChatGroupDO::getLastChatTime, reqVO.getLastChatTime())
                .betweenIfPresent(WeChatGroupDO::getCreateTime, reqVO.getCreateTime())
                .orderByDesc(WeChatGroupDO::getLastChatTime);
        return selectJoinPage(reqVO, WeChatGroupDO.class, query);
    }
}